package com.ponhu.ea2.goodsCenter.provider.biz;

import com.ponhu.ea2.goodsCenter.provider.mapper.PonHuGoodsTradePriceInfoMapper;
import com.ponhu.ea2.goodsCenter.provider.utils.SpeechSynthesizerUtil;
import com.ponhu.ea2.properties.GoodsProperties;
import com.ponhu.ea2.vo.PonHuGoodsTradePriceInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaokai
 */
@Slf4j
@Service
@RefreshScope
public class PonHuGoodsService {

    private Integer LIST_LIMIT = 50;

    @Resource
    GoodsProperties goodsProperties;

    @Resource
    private PonHuGoodsTradePriceInfoMapper ponHuGoodsTradePriceInfoMapper;

    /**
     * 自定义线程池,核心线程为5,最大线程为20,队列为500
     */
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2000), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());

    private String appKey = "mgsqz8vnnf158EAS";
    private String id = "LTAI5tKMSE9vURwdsbiLAKMW";
    private String secret = "VIusIuRWyy6FbpCIYWhwmkivlJuq4M";
    private String url = "wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1";

    public void processData(List<PonHuGoodsTradePriceInfoVo> list) {
        try {
            // 开启线程超时自动关闭
            threadPoolExecutor.allowCoreThreadTimeOut(true);
            // 先分组数据
//            List<List<PonHuGoodsTradePriceInfoVo>> parts = Lists.partition(list, LIST_LIMIT);
            if (CollectionUtils.isNotEmpty(list)) {
//                CompletableFuture<Void> initSelling = CompletableFuture.runAsync(() -> {
                list.stream().forEach(item -> {
                    // 处理数据逻辑
                    String audioUrl = processSellingPointAudioUrl(item.getGoodsSelling());
                    log.info("{} ,音频地址：{}", item.getInventoryCode(), audioUrl);
                    ponHuGoodsTradePriceInfoMapper.updateGoodsSellingAudioUrl(item.getInventoryCode(), audioUrl);
                });
//                }, threadPoolExecutor);
            }
        } catch (Exception e) {
            log.error("处理胖总管商品卖点音频任务异常：{}", e);
            throw e;
        }
    }

    /**
     * 处理卖点音频地址
     * 传入值为空，则使用默认卖点信息
     *
     * @param goodsSellingPoint 商品卖点
     * @return 语音Mp3地址
     */
    public String processSellingPointAudioUrl(String goodsSellingPoint) {
        SpeechSynthesizerUtil speechSynthesizerUtil = new SpeechSynthesizerUtil(appKey, id, secret, url);
        String sellingAudioUrl;
        if (StringUtils.isBlank(goodsSellingPoint)) {
//            sellingAudioUrl = speechSynthesizerUtil.process(defaultGoodsSelling);
            if (StringUtils.isBlank(goodsProperties.getDefaultGoodsSellingAudioUrl()))
                throw new RuntimeException("默认商品卖点的文案转语音URL未配置");
            return goodsProperties.getDefaultGoodsSellingAudioUrl();
        } else {
            sellingAudioUrl = speechSynthesizerUtil.process(goodsSellingPoint.trim());
        }
        speechSynthesizerUtil.shutdown();
        return sellingAudioUrl;
    }
}
